<template>
  <div class="">
    <el-form
      ref="form_ref"
      :inline="true"
      :rules="rules"
      :model="info.form"
      class="mt-30px"
    >
      <el-form-item label="外链地址:" prop="url">
        <el-input
          v-model="info.form.url"
          placeholder="请输入外链地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="上传图片:" prop="img">
        <div class="mt--30px">
          <!-- <div>
            <el-image
              :src="info.form.img"
              :zoom-rate="1.2"
              :preview-src-list="[info.form.img]"
              :initial-index="4"
              fit="cover"
              class="w-100px"
            />
          </div> -->
          <div>
            <el-upload
              v-model:file-list="info.imgList"
              accept=".png, .jpg, .jpeg"
              class="mt-20px"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-icon size="50px" color="#409EFC">
                <Upload />
              </el-icon>
              <!-- <el-button type="primary">上传图片</el-button> -->
            </el-upload>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update('update')">修改提交</el-button>
        <!-- <el-button type="primary" @click="update('reset')">重置</el-button> -->
      </el-form-item>
    </el-form>
    <Banner :list="info.carouselList" />
    <el-table
      :data="info.bannerList"
      
      ref="multipleTable"
      type="selection"
      class="mt-30px"
      @selection-change="selectItem"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="顺序" width="180" />
      <el-table-column prop="img" label="图片" width="180" align="center">
        <template #default="scope">
          <el-image
            class="w-100px"
            :src="scope.row.img"
            v-if="scope.row.img"
          />
          <p v-else>无</p>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="外链地址">
        <template #default="scope">
          <p>{{ scope.row.url || "无" }}</p>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import Banner from "./components/banner.vue";
import { update_banner_img, manage_banner_list } from "@/api/back/banner";
import * as imageConversion from "image-conversion";
import { rules } from "./data.config";

const form_ref = ref(null);
const multipleTable = ref(null);
const info = reactive({
  multipleSelection: [],
  bannerList: [],
  carouselList: [],
  row: {},
  currentId: "",
  form: {
    url: "www.baidu.com",
    id: "",
    img: "",
  },
  id: "",
  // 上传文件的列表
  imgList: [],
  dialogImageUrl: "", //上传图片后的图片地址
  uploadImgBase64: "", //存储将图片转化为base64后的字符
});

const selectItem = (rows) => {
  if (rows.length) {
    info.form.id = rows[0].id;
  }

  if (rows.length > 1) {
    const newRows = rows.filter((it, index) => {
      if (index == rows.length - 1) {
        multipleTable.value.toggleRowSelection(it, true);
        return true;
      } else {
        multipleTable.value.toggleRowSelection(it, false);
        return false;
      }
    });
  }
};

const getBanner = async () => {
  const { data } = await manage_banner_list();
  info.bannerList = data;
  info.carouselList = data.filter((item) => item.img);
};
getBanner();

const handleRemove = (file) => {
  info.imgList = [];
  info.form.img = "";
};

//修改
const update = async (type) => {
  if (!info.form.id) return ElMessage.error("请在表格中勾选!");
  if (!info.form.img) return ElMessage.error("请上传图片!");

  await form_ref.value.validate(async (valid, fields) => {
    if (valid) {
      const { code } = await update_banner_img(info.form);
      if (code === 200) {
        getBanner();
        ElMessage.success("修改成功！");
      } else {
        ElMessage.error("修改失败");
      }
    }
  });
};

const handlePictureCardPreview = (file) => {
  info.dialogImageUrl = file.url;
};

// 上传前勾子函数
const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过2MB");
    return false;
  } else {
    const isSize = new Promise((resolve, reject) => {
      const _URL = window.URL || window.webkitURL;
      const img = new Image();
      img.onload = () => {
        const valid = true;
        valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        return file;
      },
      () => {
        ElMessage.error("上传图片大小不能超过2MB");
        return Promise.reject();
      }
    );
    isSize.then((file) => {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 100;
      if (!isJpgOrPng) {
        ElMessage.error("上传图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      return new Promise((resolve) => {
        // 小于100KB 不压缩
        if (isLt2M) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 50).then((res: any) => {
          toBase64(res);
          resolve(res);
        });
      });
    });
  }
  return false; //取消自动上传
};

const handleAddFeedback = () => {
  let self = this;
  if (!self.addFeedbackInfo) {
    ElMessage.warning("反馈消息不能为空");
  } else {
    let addFeedbackForm = {};
    addFeedbackForm.StudentInf = self.addFeedbackInfo;
    addFeedbackForm.StudentImg = self.uploadImgBase64;
  }
};
// 删除已上传图片
const delUploadImg = () => {
  info.dialogImageUrl = "";
  info.uploadImgBase64 = "";
};
// 将图片转为base64
const toBase64 = (file) => {
  let reader = new FileReader();
  reader.onloadend = function () {
    info.imgList = [];
    info.form.img = reader.result;
    info.imgList.push({ name: "封面图片", url: info.form.img });
  };
  if (file) {
    reader.readAsDataURL(file);
  }
};
</script>

<style scoped lang="scss">
:deep .el-form--inline .el-form-item {
  vertical-align: top;
}
</style>
